use std::{env, fs};

fn main() {
    // 收集命令行参数
    let args: Vec<String> = env::args().collect();
    // 检查是否提供了文件名
    if args.len() < 2 {
        eprintln!("Usage: {} <filename>", args[0]);
        std::process::exit(1);
    }

    // 获取文件名
    let filename = &args[1];

    // 读取输入文件
    let input = fs::read_to_string(filename).expect("Failed to read file");
    
    
    //compiler::lexer0::tokenize(&input.clone());

    //let tokens = compiler::lexer1::tokenize(&input);
    let tokens = compiler::lexer_lite::tokenize(&input);
    for token in tokens {
        eprintln!("{} {} at Line {}.", token.rule, token.value, token.line);
    }

    //test(&filename, input);
}
fn test(filename:&String, input:String) {

    let result_filename = match std::path::Path::new(filename).with_extension("result").to_str() {
        Some(s) => s.to_string(),
        None => {
            eprintln!("Invalid filename: {}", filename);
            std::process::exit(1);
        }
    };
    println!("Compare Result file: {}", result_filename);

    let expected_output = fs::read_to_string(&result_filename).unwrap_or_else(|_| {
        eprintln!("Failed to read result file: {}", result_filename);
        std::process::exit(1);
    });

    // 重新生成输出内容
    let output: String = compiler::lexer_lite::tokenize(&input)
        .into_iter()
        .map(|token| format!("{} {} at Line {}.", token.rule, token.value, token.line))
        .collect::<Vec<_>>()
        .join("\n");

    
    // 逐行对比 expected_output 和 output
    let output_lines: Vec<_> = output.lines().collect();
    let expected_lines: Vec<_> = expected_output.lines().collect();
    let max_lines = output_lines.len().max(expected_lines.len());
    let mut has_error = false;
    for i in 0..max_lines {
        let out_line = output_lines.get(i).unwrap_or(&"<no line>");
        let exp_line = expected_lines.get(i).unwrap_or(&"<no line>");
        if out_line != exp_line {
            println!("====================Line {} differs:", i + 1);
            println!("  output  : {}", out_line);
            println!("  expected: {}", exp_line);
            has_error = true;
        }
    }
    if !has_error {
        println!("Success");
    }
}
